#ifndef __ITEM_LIST_H__
#define __ITEM_LIST_H__
#include <assert.h>
#include <stddef.h>
#include <iostream>
#include "TextParser.h"

template<typename T>
class ItemList {
private:
    T * pItems;
    short nCount;
public:
    ItemList();
    ~ItemList();
    bool LoadItems(const char *szFileName, const char cRecordHead);
    inline short Count(){return nCount;}
    void List();
    short Index(const char *szName);
    T & operator[] (short i);
};

template<typename T>
ItemList<T>::ItemList()
{
    nCount = 0;
    pItems = NULL;
}

template<typename T>
ItemList<T>::~ItemList()
{
	if(pItems)
	{
		delete [] pItems;
		pItems = NULL;
	}
}

template<typename T>
bool ItemList<T>::LoadItems(const char *szFileName, const char cRecordHead)
{
	if(pItems)
	{
		delete [] pItems;
		pItems = NULL;
	}

	CTextParser ItemsFile( szFileName, cRecordHead);
	nCount = ItemsFile.GetRecordNum();
	pItems = new T[nCount];
	assert(pItems);

	for( short i = 0; i < nCount; i++)
	{
        pItems[i].Load(ItemsFile);
    }
    return true;
}

template<typename T>
T & ItemList<T>::operator[] (short i)
{
    assert( i >= 0 && i < nCount );
    return pItems[i];
}

template<typename T>
void ItemList<T>::List()
{
    for(int i = 0; i < nCount; i++){
        std::cout << i << ": " << pItems[i].szName << std::endl;
    }
}

template<typename T>
short ItemList<T>::Index(const char *szName)
{
    short index = -1;
    std::string query(szName);
    for(int i = 0; i < nCount; i ++) {
        std::string itemName(pItems[i].szName);
        if(query == itemName){
            index = i;
            break;
        }
    }
    return index;
}

#endif
